package com.sskj.fabi.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.MD5Util;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.fabi.bean.FabiListBean;
import com.sskj.fabi.ui.activity.FabiPublishActivity;
import com.sskj.fabi.util.MathUtils;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.adapter.BaseAdapter;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;

import com.sskj.common.util.ToastUtil;

import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.TradingHallBuyPresenter;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;

import com.sskj.lib.Constans;

import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.PageBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppOuterCheckUtil;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * 法币Fragment--交易大厅--求购/出售大厅
 */
public class TradingHallBuyFragment extends BaseFragment<TradingHallBuyPresenter> {

    @BindView(R2.id.img_fabu)
    ImageView imgFabu;
    @BindView(R2.id.trading_hall_buy)
    RecyclerView tradingHallBuy;
    @BindView(R2.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private boolean isBuy; // true 购买  false出售
    private BaseAdapter<FabiListBean> mAdapter;
    private int PAGE_SIZE = 6;
    private int PAGE = 1;
    private BottomSheetDialog sellDialog;
    private List<String> list = new ArrayList<>();
    private String cKprice;  // 发布参考价
    DisposableSubscriber disposableSubscriber;
    private boolean editPriceFlag = true;// 判断用户在那个输入框输入  默认第一个 数量
    private boolean editNumFlag = false;// 判断用户在那个输入框输入  默认第一个 数量
    private int typeNumEditFilter = 4;  //数量小数点位
    private int typePriceEditFilter = 2;//价格小数点位
    private EditText editNum;
    private EditText editPrice;
    private boolean isPrice = true;  // 根据价格计算数量

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_fragment_trading_hall_buy;
    }

    @Override
    protected TradingHallBuyPresenter getPresenter() {
        return new TradingHallBuyPresenter();
    }

    /**
     * 求购大厅  出售大厅
     */
    public static TradingHallBuyFragment newInstance(boolean isBuy) {
        Bundle args = new Bundle();
        TradingHallBuyFragment fragment = new TradingHallBuyFragment();
        args.putBoolean(Constans.FABITYPE, isBuy);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                if (userData != null && userData.getIs_trans() == 0) {
                    imgFabu.setVisibility(View.GONE);
                } else {
                    imgFabu.setVisibility(View.VISIBLE);
                }
            } else {
                userData = null;
            }
        });
        userViewModel.update();
        tradingHallBuy.setLayoutManager(new LinearLayoutManager(getActivity()));
        tradingHallBuy.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setLastDraw(false)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.fabi_backgroud))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 10)));
        isBuy = (boolean) getArguments().get(Constans.FABITYPE);

        mAdapter = new BaseAdapter<FabiListBean>(R.layout.fabi_recy_item_fabi, null, tradingHallBuy) {
            @Override
            public void bind(ViewHolder holder, FabiListBean item) {
                item.setBuy(isBuy);
                holder.setText(R.id.tv_photo, item.getRealname().substring(0, 1));  //
                holder.setText(R.id.tv_name, item.getRealname());
                holder.setText(R.id.tv_price, "¥ " + item.getPrice());
                holder.setText(R.id.tv_money, NumberUtil.keep4(item.getDealsNum()));  // 成单数
                holder.setText(R.id.tv_percent, item.getRate());
                holder.setText(R.id.tv_num, "数量 " + NumberUtil.keep4(item.getTransNum() - item.getDealsNum()) + " BDD");  // 交易数量
                holder.setText(R.id.tv_limit_money, "限额 " + "¥" + item.getMinPrice() + " - ¥" + item.getMaxPrice());
                ((ImageView) holder.getView(R.id.iv_wechat)).setVisibility("1".equals(item.getPay_wx()) ? View.VISIBLE : View.GONE);
                ((ImageView) holder.getView(R.id.iv_bank)).setVisibility("1".equals(item.getPay_backcard()) ? View.VISIBLE : View.GONE);
                ((ImageView) holder.getView(R.id.iv_alipay)).setVisibility("1".equals(item.getPay_alipay()) ? View.VISIBLE : View.GONE);
                ((ImageView) holder.getView(R.id.iv_paypal)).setVisibility("1".equals(item.getPaypal()) ? View.VISIBLE : View.GONE);
                ClickUtil.click(holder.getView(R.id.item_buy_sell), () -> {  // 购买  出售
                    if (userData == null) {  // 登录状态
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiTradingHallBuyFragment7));
                        ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                        return;
                    }

                    if (!isBuy) {  // 卖出  支付方式判断 ture 购买
                        if (!AppOuterCheckUtil.checkPayType(getActivity(), userData)) {
                            return;
                        }
                    } else {
                        if (!AppOuterCheckUtil.checkTradePwd(getActivity(), userData)) {  // 买入  // 支付密码判断
                            return;
                        }
                    }
                    if (isBuy) {
                        if (SPUtil.get(SPConfig.ACCOUNT, "").equals(item.getAccount())) {   // id比较
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiTradingHallBuyFragment9));
                            return;
                        }
                        showSell(item);

                    } else {
                        if (SPUtil.get(SPConfig.ACCOUNT, "").equals(item.getAccount())) {   // id比较
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiTradingHallBuyFragment11));
                            return;
                        }
                        showSell(item);
                    }
                });
            }
        };
        mAdapter.setEmptyView();

        imgFabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userData == null) {  // 登录状态
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiFaBiFragment2));
                    ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                    return;
                }

                if (!AppOuterCheckUtil.checkPayType(getActivity(), userData)) {  // 判断是否有支付方式
                    return;
                }
                FabiPublishActivity.start(getActivity());
            }
        });

        smartRefreshView.setOnRefreshListener(refreshLayout1 -> {  // 下拉刷新
            smartRefreshView.finishRefresh();
            PAGE = 1;
            mPresenter.getFabiList(PAGE, PAGE_SIZE, isBuy);
        });
        smartRefreshView.setOnLoadMoreListener(new OnLoadMoreListener() {  // 上拉加载
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                smartRefreshView.finishLoadMore();
                PAGE++;
                mPresenter.getFabiList(PAGE, PAGE_SIZE, isBuy);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
    }

    public void setData(PageBean<FabiListBean> httpData) {
        if (PAGE == 1) {
            mAdapter.setNewData(httpData.getList());
        } else {
            mAdapter.addData(httpData.getList());
        }
        cKprice = httpData.getCk_price();
    }


    /**
     * 显示销售底部弹窗
     */
    private void showSell(FabiListBean item) {

        sellDialog = new BottomSheetDialog(getActivity());

        double overNumber = item.getTransNum() - item.getDealsNum();  // 计算剩余数量
        double maxPrice; // 最大可购买金额
        if (overNumber * Double.valueOf(item.getPrice()) > item.getMaxPrice()) {
            isPrice = true;
            maxPrice = Double.valueOf(item.getMaxPrice());
        } else {
            isPrice = false;
            maxPrice = overNumber * Double.valueOf(item.getPrice());
        }
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.fabi_bottom_sheet_trade_type, null);
        ((TextView) dialogView.findViewById(R.id.trade_type)).setText(isBuy ? "购买BDD" : "出售BDD");
        TextView allBuy = (TextView) dialogView.findViewById(R.id.all_buy);
        allBuy.setText(isBuy ? "全部买入" : "全部卖出");
        ((TextView) dialogView.findViewById(R.id.type_price)).setText("¥ " + item.getPrice());
        ((TextView) dialogView.findViewById(R.id.tv_limit_money)).setText("限额 " + "¥" + item.getMinPrice() + " - ¥" + item.getMaxPrice());
        ((TextView) dialogView.findViewById(R.id.iv_wechat)).setVisibility("1".equals(item.getPay_wx()) ? View.VISIBLE : View.GONE);
        ((TextView) dialogView.findViewById(R.id.iv_bank)).setVisibility("1".equals(item.getPay_backcard()) ? View.VISIBLE : View.GONE);
        ((TextView) dialogView.findViewById(R.id.iv_alipay)).setVisibility("1".equals(item.getPay_alipay()) ? View.VISIBLE : View.GONE);
        ((TextView) dialogView.findViewById(R.id.iv_paypal)).setVisibility("1".equals(item.getPaypal()) ? View.VISIBLE : View.GONE);
        editPrice = (EditText) dialogView.findViewById(R.id.edit_price);
        editPrice.setHint((isBuy ? "最大可购买金额 " : "最大可出售金额") + NumberUtil.keep2(maxPrice));
        editNum = (EditText) dialogView.findViewById(R.id.edit_num);
        editNum.setHint((isBuy ? "最大可购买数量" : "最大可出售数量") + NumberUtil.keep4(maxPrice / Double.valueOf(item.getPrice())));
        editNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(typeNumEditFilter)});
        Button btCancel = dialogView.findViewById(R.id.btCancel);
        ClickUtil.click(btCancel, () -> {
            sellDialog.dismiss();
        });
        editPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(typePriceEditFilter)});
        ClickUtil.click(allBuy, () -> {
            if (isPrice) {
                editNumFlag = false;
                editPriceFlag = false;
                editPrice.clearFocus();
                editNum.clearFocus();
                editPrice.setText(NumberUtil.keep2(maxPrice));
                String s = NumberUtil.keep2(maxPrice);
                editNum.setText(NumberUtil.keep4(String.valueOf(Double.valueOf(TextUtils.isEmpty(s.toString()) ? "0.0000" : MathUtils.divide(s.toString(), item.getPrice() + "", 4)))));
            } else {
                editNum.setFocusable(true);
                editNum.setFocusableInTouchMode(true);
                editNum.requestFocus();
                editNum.setText(NumberUtil.keep4(item.getTransNum() - item.getDealsNum()));
            }
        });
        EditText editPwd = (EditText) dialogView.findViewById(R.id.etPwd);

        startCount(btCancel);
        ((Button) dialogView.findViewById(R.id.btLogin)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String edPrice = editPrice.getText().toString().trim();
                String edNum = editNum.getText().toString().trim();
                if (TextUtils.isEmpty(edPrice)) {
                    ToastUtil.showShort("请输入金额");
                    return;
                }
                if (Double.valueOf(edPrice) < Double.valueOf(item.getMinPrice())) {
                    ToastUtil.showShort("当前金额<最小限额" + item.getMinPrice());
                    return;
                }
                if (Double.valueOf(edPrice) > Double.valueOf(item.getMaxPrice())) {
                    ToastUtil.showShort("当前金额>最大限额" + item.getMaxPrice());
                    return;
                }
                if (TextUtils.isEmpty(edNum)) {
                    ToastUtil.showShort("请输入数量");
                    return;
                }
                if (TextUtils.isEmpty(editPwd.getText().toString().trim())) {
                    ToastUtil.showShort("请输入支付密码");
                    return;
                }
                mPresenter.order(MD5Util.getMd5Value(editPwd.getText().toString().trim()), item.getOrder_no(), editNum.getText().toString().trim(), editPrice.getText().toString().trim(), isBuy);
            }
        });
        initEditText(item);
        sellDialog.setContentView(dialogView);
        sellDialog.show();
    }

    public void startCount(Button btCancel) {
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @SuppressLint("StringFormatMatches")
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                btCancel.setText(String.format(App.INSTANCE.getString(R.string.fabibtCancel), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                sellDialog.dismiss();

            }
        };

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DisposUtil.close(disposableSubscriber);
    }

    public void checkOk(String orderNum, boolean isBuy) {
        sellDialog.dismiss();
        ARouter.getInstance().build(RConfig.FABI_ORDER_DETAIL)
                .withString("orderNum", orderNum)
                .navigation();
    }

    /**
     * 处理EditText输入显示联动问题
     */
    public void initEditText(FabiListBean item) {
        editNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editNumFlag = true;
                    editPriceFlag = false;
                }
            }
        });
        editPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editPriceFlag = true;
                    editNumFlag = false;
                }
            }
        });
        editNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editNumFlag && !"0".equals(item.getPrice())) {
//                    orderDetailPriceEdit.setText(String.valueOf(Double.valueOf(TextUtils.isEmpty(s.toString()) ? "0.00" : String.valueOf(new BigDecimal(s.toString()).multiply(new BigDecimal(fabiListBean.getPrice() + "")).doubleValue()))));
                    editPrice.setText(NumberUtil.keep2(Double.valueOf(TextUtils.isEmpty(s.toString()) ? "0.0000" : s.toString()) * Double.valueOf(item.getPrice()) + ""));
                }
            }
        });
        editPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editPriceFlag && !"0".equals(item.getPrice())) {
                    editNum.setText(NumberUtil.keep4(String.valueOf(Double.valueOf(TextUtils.isEmpty(s.toString()) ? "0.0000" : MathUtils.divide(s.toString(), item.getPrice() + "", 4)))));
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        PAGE = 1;
        mPresenter.getFabiList(PAGE, PAGE_SIZE, isBuy);
    }
}
